Skip to content

Latest commit

 

History

History
102 lines (83 loc) · 3.04 KB

File metadata and controls

102 lines (83 loc) · 3.04 KB

76. Minimum Window Substring

Given two strings s and t of lengths m and n respectively, return the minimum window substring ofssuch that every character int(including duplicates) is included in the window. If there is no such substring, return the empty string"".

The testcases will be generated such that the answer is unique.

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. 

Example 2:

Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window. 

Example 3:

Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. 

Constraints:

  • m == s.length
  • n == t.length
  • 1 <= m, n <= 105
  • s and t consist of uppercase and lowercase English letters.

Follow up: Could you find an algorithm that runs in O(m + n) time?

Solutions (Rust)

1. Solution

implSolution{pubfnmin_window(s:String,t:String) -> String{if s.len() < t.len(){returnString::new();}let s = s.as_bytes();let t = t.as_bytes();letmut count_s = [0;52];letmut count_t = [0;52];letmut sub_indices = (0, s.len() + 1);letmut i = 0;letmut j = 0;while j < t.len(){match s[j]{b'A'..=b'Z' => count_s[(s[j] - b'A')asusize] += 1, _ => count_s[(s[j] - b'a')asusize + 26] += 1,}match t[j]{b'A'..=b'Z' => count_t[(t[j] - b'A')asusize] += 1, _ => count_t[(t[j] - b'a')asusize + 26] += 1,} j += 1;}if(0..52).all(|k| count_s[k] >= count_t[k]){ sub_indices = (i, j);}while j < s.len(){while j < s.len() && (0..52).any(|k| count_s[k] < count_t[k]){match s[j]{b'A'..=b'Z' => count_s[(s[j] - b'A')asusize] += 1, _ => count_s[(s[j] - b'a')asusize + 26] += 1,} j += 1;}while(0..52).all(|k| count_s[k] >= count_t[k]){if j - i < sub_indices.1 - sub_indices.0{ sub_indices = (i, j);}match s[i]{b'A'..=b'Z' => count_s[(s[i] - b'A')asusize] -= 1, _ => count_s[(s[i] - b'a')asusize + 26] -= 1,} i += 1;}}if sub_indices.1 - sub_indices.0 > s.len(){returnString::new();}String::from_utf8(s[sub_indices.0..sub_indices.1].to_vec()).unwrap()}}
close